#region Using

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using BlogEngine.Core;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

#endregion

namespace BlogEngine.Core.Provider.LocalFileSystem
{
	public class CIPhotoStorage
	{

		/// <summary>
		/// Gets a name of the unique file.
		/// </summary>
		/// <param name="photo">The photo.</param>
		/// <returns></returns>
		protected string GetUniqueFileName(Photo photo)
		{
			if (!File.Exists(System.IO.Path.Combine(Provider.Folder, System.IO.Path.Combine(Provider.Folder, photo.OriginalFileName))))
				return photo.OriginalFileName;

			string ext = Path.GetExtension(photo.OriginalFileName);
			string woext = Path.GetFileNameWithoutExtension(photo.OriginalFileName);

			return ext + "-" + photo.Id.ToString() + "." + woext;
		}

		/// <summary>
		/// Saves the specified photo.
		/// </summary>
		/// <param name="photo">The photo.</param>
		/// <param name="file">The file.</param>
		public void Save(Photo photo, Stream file)
		{
			if (string.IsNullOrEmpty(photo.Location))
				photo.Location = System.IO.Path.Combine(Provider.Folder, GetUniqueFileName(photo));

			StorePhoto(file, System.IO.Path.Combine(Provider.Folder, photo.Location));
		}


		/// <summary>
		/// Deletes the specified photo.
		/// </summary>
		/// <param name="photo">The photo.</param>
		public void Delete(Photo photo)
		{
			File.Delete(System.IO.Path.Combine(Provider.Folder, photo.Location));
		}

		/// <summary>
		/// Loads the specified photo.
		/// </summary>
		/// <param name="photo">The photo.</param>
		/// <returns></returns>
		public Stream Load(Photo photo)
		{
			return File.OpenRead(System.IO.Path.Combine(Provider.Folder, photo.Location));
		}

		/// <summary>
		/// Stores the photo.
		/// </summary>
		/// <param name="file">The file.</param>
		/// <param name="filename">The filename.</param>
		protected static void StorePhoto(Stream file, string filename)
		{
			using (FileStream fs = new FileStream(filename, FileMode.CreateNew))
			{
				file.Seek(0, SeekOrigin.Begin);
				Byte[] buffer = new Byte[4096];

				int bytesRead = file.Read(buffer, 0, buffer.Length);
				while (bytesRead > 0)
				{
					fs.Write(buffer, 0, bytesRead);
					bytesRead = file.Read(buffer, 0, buffer.Length);
				}

				fs.Flush();
			}
		}
	}
}
